<template>
  <el-dialog
    ref="dialog"
    class="dialog alltransition"
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :width="options.width"
    :before-close="onBeforeClose"
    @closed="onClosed"
  >
    <div ref="component" id="component"></div>
    <span
      v-if="!options.nofooter"
      ref="footer"
      slot="footer"
      class="dialog-footer"
    >
    </span>
  </el-dialog>
</template>

<script>
import Vue from "vue";
export default {
  name: "window",
  data: () => ({
    component: null,
    title: "编辑",
    dialogVisible: false,
    options: {
      width: "50%",
      nopadding: false,
      nofooter: true
    },
    instance: {}
  }),
  mounted() {},
  watch: {
    dialogVisible(v) {
      if (!this.component) {
        return;
      }
      if (v) {
        // this.$nextTick(() => {
        //   const component = Vue.extend(this.component);
        //   this.instance = new component({
        //     el: "#component",
        //     data: { ...this.options, thisDialog: this }
        //   });
        // });
      }
    }
  },
  methods: {
    show(opt) {
      this.dialogVisible = true;
      let data = Object.assign(this.instance, opt, {
        thisDialog: this,
        close: () => {
          this.close();
        }
      });
      this.$nextTick(() => {
        const component = Vue.extend(this.component);
        this.instance = new component({
          el: "#component",
          data: { ...data }
        });
        let footer = this.instance.$refs.footer;
        if (footer && footer.innerHTML) {
          this.options.nofooter = false;
          this.$nextTick(() => {
            this.$refs.footer.insertAdjacentHTML("beforeend", footer.innerHTML);
          });
        }
        if (this.options.nopadding) {
          this.$refs.dialog.$el.classList.add("nopadding");
        }
        // console.log(this.instance);
        // console.log(this.instance.$refs.footer);
      });
      return this;
    },
    close() {
      this.dialogVisible = false;
    },
    onClosed() {
      console.log("close");
      this.$destroy();
    },
    onBeforeClose(done) {
      // this.$el.removeChild(this.$refs.component.$el);
      this.instance.$destroy();
      done();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog {
  /deep/ .el-dialog__body {
    max-height: 60vh;
    overflow: auto;
  }
}
.nopadding {
  /deep/ .el-dialog__body {
    padding: 5px;
  }
}
.dialog-footer {
  visibility: hidden;
}
</style>
